<template>
  <div class="tasks">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>任务列表</span>
          <el-input
            v-model="searchTaskId"
            placeholder="搜索任务ID"
            class="search-input"
            clearable
            @keyup.enter="handleSearch"
          >
            <template #suffix>
              <el-icon class="search-icon" @click="handleSearch"><Search /></el-icon>
            </template>
          </el-input>
        </div>
      </template>

      <el-table :data="tasks" v-loading="loading" style="width: 100%">
        <el-table-column prop="taskId" label="任务ID" width="180" />
        <el-table-column prop="url" label="URL" show-overflow-tooltip>
          <template #default="{ row }">
            <el-link type="primary" :href="row.url" target="_blank">{{ row.url }}</el-link>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button 
              type="primary" 
              link 
              :disabled="row.status !== 2"
              @click="handlePreview(row)"
            >
              预览
            </el-button>
            <el-button 
              type="primary" 
              link 
              :disabled="row.status !== 2"
              @click="handleDownload(row)"
            >
              下载
            </el-button>
            <el-button 
              type="danger" 
              link
              @click="handleDelete(row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination
          :current-page="currentPage"
          :page-size="pageSize"
          :total="total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next"
          @update:current-page="currentPage = $event"
          @update:page-size="pageSize = $event"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 预览对话框 -->
    <el-dialog
      v-model="previewVisible"
      title="预览图片"
      width="80%"
      :destroy-on-close="true"
    >
      <div class="preview-container">
        <img :src="previewUrl" alt="预览图片" style="max-width: 100%;" />
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import { useRoute } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search } from '@element-plus/icons-vue'
import screenshotApi from '../api/screenshot'

const route = useRoute()
const loading = ref(false)
const tasks = ref([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)
const searchTaskId = ref('')
const previewVisible = ref(false)
const previewUrl = ref('')

// 状态映射
const statusMap = {
  0: { type: 'info', text: '待处理' },
  1: { type: 'warning', text: '处理中' },
  2: { type: 'success', text: '成功' },
  3: { type: 'danger', text: '失败' }
}

const getStatusType = (status) => statusMap[status]?.type || 'info'
const getStatusText = (status) => statusMap[status]?.text || '未知'

// 加载任务列表
const loadTasks = async () => {
  loading.value = true;
  try {
    const params = {
      page: currentPage.value - 1, // Spring Data JPA 的页码从0开始
      size: pageSize.value
    };
    
    if (searchTaskId.value) {
      params.taskId = searchTaskId.value;
    }
    
    const { data } = await screenshotApi.getTasks(params);
    tasks.value = data.data.content;
    total.value = data.data.totalElements;
  } catch (error) {
    ElMessage.error('加载任务列表失败');
  } finally {
    loading.value = false;
  }
};

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  loadTasks()
}

// 分页
const handleSizeChange = (val) => {
  pageSize.value = val
  loadTasks()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  loadTasks()
}

// 预览
const handlePreview = async (row) => {
  try {
    const response = await screenshotApi.getTaskResult(row.taskId)
    previewUrl.value = URL.createObjectURL(response.data)
    previewVisible.value = true
  } catch (error) {
    ElMessage.error('加载预览图片失败')
  }
}

// 下载
const handleDownload = async (row) => {
  try {
    const response = await screenshotApi.getTaskResult(row.taskId)
    const url = URL.createObjectURL(response.data)
    const link = document.createElement('a')
    link.href = url
    link.download = `screenshot-${row.taskId}.${row.format}`
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    URL.revokeObjectURL(url)
  } catch (error) {
    ElMessage.error('下载失败')
  }
}

// 删除
const handleDelete = (row) => {
  ElMessageBox.confirm(
    '确定要删除该任务吗？',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(async () => {
    try {
      // TODO: 实现后端删除API
      await screenshotApi.deleteTask(row.taskId)
      ElMessage.success('删除成功')
      loadTasks()
    } catch (error) {
      ElMessage.error('删除失败')
    }
  })
}

// 定时刷新任务状态
let refreshTimer = null;

onMounted(() => {
  // 如果URL中有taskId参数，设置到搜索框
  if (route.query.taskId) {
    searchTaskId.value = route.query.taskId
  }
  loadTasks();
  // 每5秒刷新一次任务列表
  refreshTimer = setInterval(loadTasks, 5000);
})

onUnmounted(() => {
  if (refreshTimer) {
    clearInterval(refreshTimer);
  }
})
</script>

<style scoped>
.tasks {
  max-width: 1200px;
  margin: 0 auto;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-input {
  width: 200px;
}

.search-icon {
  cursor: pointer;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.preview-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 200px;
}
</style> 